package com.returnsoft.security.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
//import javax.jws.WebService;

import com.returnsoft.security.dto.DepartmentDto;
import com.returnsoft.security.dto.PermissionDto;
import com.returnsoft.security.dto.UserDto;
import com.returnsoft.security.eao.DepartmentEao;
import com.returnsoft.security.eao.PermissionEao;
import com.returnsoft.security.eao.PersonEao;
import com.returnsoft.security.eao.UserEao;
import com.returnsoft.security.entity.Department;
import com.returnsoft.security.entity.Person;
import com.returnsoft.security.entity.User;
import com.returnsoft.security.exception.ConversionExcepcion;
import com.returnsoft.security.exception.EaoExcepcion;
import com.returnsoft.security.exception.SecurityExcepcion;
import com.returnsoft.security.util.Conversion;

/**
 * Session Bean implementation class UserBean
 */
@Stateless
@LocalBean
public class UserBean implements UserInterface, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	private UserEao userEao;
	@EJB
	private PersonEao personEao;
	@EJB
	private PermissionEao permissionEao;
	@EJB
	private DepartmentEao departmentEao;
	@EJB
	private Conversion conv;

	@Override
	public UserDto doLogin(String username, String password,
			List<String> permissionsCode) throws SecurityExcepcion {
		try {
			// OBTIENE EL USER
			
			UserDto user = userEao.findByUsername(username);
			
			if (user != null && user.getId() > 0) {

				if (user.getPassword().equals(password)) {
					if (user.getIsActive()) {
						// OBTIENE LOS PERMISSIONS
						List<PermissionDto> permissions = permissionEao
								.findByUser(user.getId());
						
						//System.out.println("antes de obtener los permisos");
						//Set<Permission> permissions = user.getPermissions();
						/*for (Permission permission : permissions) {
							System.out.println(permission.getCode());
						}*/
						//System.out.println("despues de obtener los permisos");
						boolean flag = false;
						for (PermissionDto permission : permissions) {
							/*PermissionDto permissionDto = conv
									.fromPermission(permission);
							permissionsDto.add(permissionDto);*/
							for (String permissionCode : permissionsCode) {
								if (permission.getCode().equals(permissionCode)) {
									flag = true;
								}
							}
						}
						if (flag) {
							//UserDto userDto = conv.fromUser(user);
							user.setPermissions(permissions);
							return user;
						} else {
							throw new SecurityExcepcion(
									"El usuario no tiene permiso.");
						}
					} else {
						throw new SecurityExcepcion(
								"El usuario se encuentra inactivo.");
					}
				} else {
					throw new SecurityExcepcion(
							"El password del usuario es incorrecto.");
				}
			} else {
				throw new SecurityExcepcion(
						"El usuario " + username + " no existe.");
			}

		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public List<UserDto> findUsers(List<Integer> departmentsId,
			List<Integer> subDepartmentsId, String documentNumber,
			String username, String firstname, String lastname)
			throws SecurityExcepcion {
		try {

			List<UserDto> users = userEao.findList(departmentsId,
					subDepartmentsId, documentNumber, username, firstname,
					lastname);
			
			return users;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public List<UserDto> findUsers(String documentNumber, String firstname,
			String lastname, String permissionCode) throws SecurityExcepcion {
		try {

			List<User> users = userEao.findUsersByPermission(documentNumber,
					firstname, lastname, permissionCode);

			List<UserDto> usersDto = new ArrayList<UserDto>();

			for (User user : users) {
				UserDto ud = conv.fromUser(user);
				usersDto.add(ud);
			}

			return usersDto;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public List<UserDto> findUsers(List<Integer> departmentsId,
			List<Integer> subDepartmentsId, String documentNumber,
			String firstname, String lastname, String username,
			String permissionCode) throws SecurityExcepcion {
		try {

			List<User> users = userEao.findUsers(departmentsId,
					subDepartmentsId, documentNumber, firstname, lastname,
					username, permissionCode);

			List<UserDto> usersDto = new ArrayList<UserDto>();

			for (User user : users) {
				UserDto ud = conv.fromUser(user);
				usersDto.add(ud);
			}

			return usersDto;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public UserDto addUser(UserDto userDto) throws SecurityExcepcion {
		try {

			User user = conv.toUser(userDto);
			if (user.getPerson() != null) {
				Person person = personEao.add(user.getPerson());
				user.setPerson(person);
			}

			System.out.println(user.getPerson().getFirstname());
			System.out.println(user.getPerson().getLastname());

			user = userEao.addUser(user);
			userDto = conv.fromUser(user);

			return userDto;

		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public UserDto findById(Integer userId) throws SecurityExcepcion {
		try {
			UserDto userDto = userEao.findById(userId);
			//UserDto ud = conv.fromUser(user);
			return userDto;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public UserDto findByPersonId(Integer personId) throws SecurityExcepcion {
		try {
			User user = userEao.findByPersonId(personId);
			UserDto ud = conv.fromUser(user);
			return ud;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public UserDto findByDocumentNumber(String documentNumber)
			throws SecurityExcepcion {
		try {
			User user = userEao.findByDocumentNumber(documentNumber);
			UserDto ud = conv.fromUser(user);
			return ud;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public List<DepartmentDto> findDepartments(Integer userId)
			throws SecurityExcepcion {
		try {
			List<DepartmentDto> departmentsDto = departmentEao.findByUser(userId);
			/*List<DepartmentDto> departmentsDto = new ArrayList<DepartmentDto>();
			for (Department department : departments) {
				DepartmentDto departmentDto = conv.fromDepartment(department);
				departmentsDto.add(departmentDto);
			}*/
			return departmentsDto;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

	@Override
	public List<PermissionDto> findPermissions(Integer userId)
			throws SecurityExcepcion {
		try {
			List<PermissionDto> permissionsDto = permissionEao.findByUser(userId);
			//List<PermissionDto> permissionsDto = new ArrayList<PermissionDto>();
			/*for (Permission permission : permissions) {
				PermissionDto permissionDto = conv.fromPermission(permission);
				permissionsDto.add(permissionDto);
			}*/
			return permissionsDto;
		} catch (EaoExcepcion e) {
			throw new SecurityExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityExcepcion(e.getMessage());
		}
	}

}
